package com.mfhcd.facepay.fragment

import android.annotation.SuppressLint
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.jakewharton.rxbinding3.view.clicks
import com.mfhcd.facepay.R
import com.mfhcd.facepay.activity.PaymentActivity
import com.mfhcd.facepay.activity.TransResultActivity
import com.mfhcd.facepay.adapter.IndexPageTagAdapter
import com.mfhcd.facepay.base.BaseFragment
import com.mfhcd.facepay.constant.ArouterUrl
import com.mfhcd.facepay.databinding.FragmentIndexBinding
import com.mfhcd.facepay.model.IndexPageModel
import com.mfhcd.facepay.model.RequestModel
import com.mfhcd.facepay.model.ResponseModel
import com.mfhcd.facepay.model.TypeModel
import com.mfhcd.facepay.utils.Convert
import com.mfhcd.facepay.utils.LogUtil
import com.mfhcd.facepay.utils.SPUtils
import com.mfhcd.facepay.utils.ToastUtil
import com.mfhcd.facepay.viewmodel.TestViewModel
import com.mfhcd.facepay.widget.GridItemDecoration
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * 首页
 */
class IndexFragment : BaseFragment<TestViewModel, FragmentIndexBinding>() {
    private lateinit var mAdapter: IndexPageTagAdapter

    companion object StaticParams {
        fun newInstance(): IndexFragment {
            return IndexFragment()
        }
    }

    override fun initContentView(): Int {
        return R.layout.fragment_index
    }

    override fun initData() {
        val lists: MutableList<IndexPageModel> = ArrayList()
        var itemModel = IndexPageModel("00", "产品应用", 0)
        var itemSubListMode: MutableList<IndexPageModel> = ArrayList()
        itemSubListMode.add(IndexPageModel("01", "结算", R.mipmap.ic_launcher_round))
        itemSubListMode.add(IndexPageModel("02", "签退", R.mipmap.ic_launcher_round))
        itemSubListMode.add(IndexPageModel("03", "管理", R.mipmap.ic_launcher_round))
        itemSubListMode.add(IndexPageModel("04", "消费撤销", R.mipmap.ic_launcher_round))
        itemSubListMode.add(IndexPageModel("05", "刷脸付退款", R.mipmap.ic_launcher_round))
        itemSubListMode.add(IndexPageModel("06", "扫码付退款", R.mipmap.ic_launcher_round))
        itemSubListMode.add(IndexPageModel("07", "设备查询", R.mipmap.ic_launcher_round))
        itemSubListMode.add(IndexPageModel("08", "本地交易查询", R.mipmap.ic_launcher_round))
        itemSubListMode.add(IndexPageModel("09", "联系客服", R.mipmap.ic_launcher_round))
        itemSubListMode.add(IndexPageModel("10", "预授权撤销", R.mipmap.ic_launcher_round))
        itemSubListMode.add(IndexPageModel("11", "预授权完成", R.mipmap.ic_launcher_round))
        itemSubListMode.add(IndexPageModel("12", "预授权完成撤销", R.mipmap.ic_launcher_round))
        itemModel.subList = itemSubListMode
        lists.add(itemModel)
        initListView(lists)
    }

    @SuppressLint("CheckResult")
    override fun initListener() {
        mAdapter.setOnMenuItemClickListener { code, name ->
            ToastUtil.showToast("$code-$name")
            when (code) {
                "04" -> {
                    doRevokeTransaction()
                }
                "10" -> {
                    doRevokePreTransaction()
                }
                else -> {
                }
            }
        }

        bindingView.ivFacepay.clicks()
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe {
                    ARouter.getInstance().build(ArouterUrl.ACTIVITY_PAYMENT).withString(PaymentActivity.TYPE_LABEL, PaymentActivity.TYPE_TRANS).navigation()
                }
        bindingView.ivFacepayPreAuth.clicks()
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe {
//                    ARouter.getInstance().build(ArouterUrl.ACTIVITY_TEST)
//                            .withBoolean("testStatus", true)
//                            .withString(Constants.MERCHANT_NO, "M89898r89389389439489")
//                            .withString(Constants.SOURCE, "test")
//                            .navigation()
                    ARouter.getInstance().build(ArouterUrl.ACTIVITY_PAYMENT).withString(PaymentActivity.TYPE_LABEL, PaymentActivity.TYPE_PRE_AUTH).navigation()
                }

    }

    private fun initListView(lists: MutableList<IndexPageModel>) {
        mAdapter = IndexPageTagAdapter(lists)
        val divider: GridItemDecoration = GridItemDecoration.Builder(getActivity())
                .setHorizontalSpan(R.dimen.dp_1)
                .setVerticalSpan(R.dimen.dp_1)
                .setColorResource(R.color.color_F8F9FA)
                .setShowLastLine(false)
                .build()
        bindingView.rvList.addItemDecoration(divider)
        bindingView.rvList.layoutManager = LinearLayoutManager(context)
        bindingView.rvList.adapter = mAdapter
    }

    /**
     * 消费撤销，测通流程，写死批次流水
     */
    private fun doRevokeTransaction() {
        var initCseqNo = "000555"
        // 序列号自增
        var cseqNo = SPUtils.getString("CSEQ_NO", initCseqNo)
        cseqNo = String.format("%06d", cseqNo.toInt() + 1)
        SPUtils.putString("CSEQ_NO", cseqNo)

        var transfer = RequestModel.TransReq()
        transfer.msG_ID = "0200"
        transfer.pan = "6214830215995142"
        transfer.prO_COD = "200000"
        transfer.cseQ_NO = cseqNo
        transfer.iN_MOD = "012"
        transfer.coN_MOD = "00"
        transfer.trM_NO = "01978239"
        transfer.merC_CD = "834491115200003"
        transfer.ccy = "156"
        transfer.resE_PRI_60 = "22000064000701"
        transfer.ttxN_AMT = "000000000100"
        // 测试写死
        transfer.orI_MES = "000064000597"
        transfer.mac = "4441334134334445"
        viewModel.doTransaction(transfer).observe(this, androidx.lifecycle.Observer { resp: ResponseModel.TransResp ->
            run {
                var message = ""
                if (resp == null) {
                    LogUtil.d("交易撤销失败")
                    message = "交易撤销失败"
                    toResultPage(false, message)
                } else {
                    LogUtil.d("交易撤销成功：\n" + Convert.toJson(resp))
                    var message = "交易撤销成功"
                    toResultPage(true, message)
                }
            }
        })
    }

    /**
     * 预授权撤销，测通流程，写死批次流水
     */
    private fun doRevokePreTransaction() {
        var initCseqNo = "000555"
        // 序列号自增
        var cseqNo = SPUtils.getString("CSEQ_NO", initCseqNo)
        cseqNo = String.format("%06d", cseqNo.toInt() + 1)
        SPUtils.putString("CSEQ_NO", cseqNo)

        var transfer = RequestModel.TransReq()
        transfer.msG_ID = "0100"
        transfer.pan = "6214830215995142"
        transfer.prO_COD = "200000"
        transfer.cseQ_NO = cseqNo
        transfer.iN_MOD = "012"
        transfer.coN_MOD = "06"
        transfer.trM_NO = "01978239"
        transfer.merC_CD = "834491115200003"
        transfer.ccy = "156"
        transfer.resE_PRI_60 = "22000064000701"
        transfer.ttxN_AMT = "000000000100"
        // 测试写死
        transfer.orI_MES = "000064000602"
        transfer.mac = "4441334134334445"
        viewModel.doTransaction(transfer).observe(this, androidx.lifecycle.Observer { resp: ResponseModel.TransResp ->
            run {
                var message = ""
                if ("00" == resp.cpscod) {
                    LogUtil.d("预授权撤销成功：\n" + Convert.toJson(resp))
                    var message = "预授权撤销成功"
                    toResultPage(true, message)
                } else {
                    LogUtil.d("预授权撤销失败")
                    message = "预授权撤销失败"
                    toResultPage(false, message)
                }
            }
        })
    }


    private fun toResultPage(isSuccess: Boolean, message: String): Any? {
        var result = TypeModel()
        result.isStatus = isSuccess
        result.remark = message
        return ARouter.getInstance().build(ArouterUrl.ACTIVITY_TRANS_RESULT)
                .withSerializable(TransResultActivity.RESULT_DATA, result)
                .navigation()
    }

}